package com.resou.reader.activity.freebook;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.resou.common.WebViewActivity;
import com.resou.reader.R;
import com.resou.reader.ReSouApplication;
import com.resou.reader.activity.friendboost.FriendBoostActivity;
import com.resou.reader.base.ToolbarActivity;
import com.resou.reader.data.bookstore.model.MorePlateInfo;
import com.resou.reader.dialog.DialogManager;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.signin.style1.SignInActivity;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.WXUtils;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.view.Loading;
import com.resou.reader.view.RippleView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class FreeBookActivity extends ToolbarActivity<FreeBookContract.Presenter> implements FreeBookContract.View {
    @BindView(R.id.wave_view)
    RippleView mRippleView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.profile_image)
    CircleImageView profileImage;
    @BindView(R.id.imageView14)
    ImageView imageView14;
    private double mItemHeight;
    private float mItemWidth;
    private int mRecyclerRightMargin;
    private int mRecyclerLeftMargin;

    public static void start(Context context) {
        Intent starter = new Intent(context, FreeBookActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    public static void start(Activity context, int state) {
        Intent starter = new Intent(context, FreeBookActivity.class);
//    starter.putExtra();
        context.startActivityForResult(starter, state);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_free_book);
        ButterKnife.bind(this);
        setTitle("15天免费活动");
        mPresenter = new FreeBookPresenter(this);

        if (UserInstance.isLogin()) {
            String headPic = UserInstance.getLoginData().getHead_pic();
            if (TextUtils.isEmpty(headPic)) {
                Glide.with(this).load(R.mipmap.user_head).into(profileImage);
            } else {
                Glide.with(this).load(headPic).into(profileImage);
            }
        }

        mRippleView.setDuration(5000);
        mRippleView.setStyle(Paint.Style.FILL);
        mRippleView.setColor(Color.RED);
        mRippleView.setInterpolator(new LinearOutSlowInInterpolator());
        mRippleView.start();

        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) recyclerView.getLayoutParams();
        mRecyclerLeftMargin = layoutParams.leftMargin;
        mRecyclerRightMargin = layoutParams.rightMargin;

        EventBus.getDefault().register(this);
        initData();
    }

    @Override
    public void setData(List<MorePlateInfo> plateInfo) {
//        int screenHeight = ScreenUtils.getScreenHeight(this);
//        float dp53 = ScreenUtils.convertDpToPixel(53, this);
//        float dp70 = ScreenUtils.convertDpToPixel(70, this);
        float itemSpacing = ScreenUtils.convertDpToPixel(15, ReSouApplication.getRSApplication());
        int screenWidth = ScreenUtils.getScreenWidth();

        mItemWidth = (screenWidth - itemSpacing * 2 - mRecyclerLeftMargin - mRecyclerRightMargin) / 3;
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                if (parent.getChildLayoutPosition(view) > 2) {
                    ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
                    layoutParams.topMargin = (int) itemSpacing;
                }
            }
        });
        mItemHeight = mItemWidth * 1.32;

        float dp33 = ScreenUtils.convertDpToPixel(33, ReSouApplication.getRSApplication());
        float dp41 = ScreenUtils.convertDpToPixel(41, ReSouApplication.getRSApplication());
        double imageHeight = mItemHeight * 2 + dp33 + dp41;
        imageView14.post(() -> imageView14.getLayoutParams().height = (int) imageHeight);
        recyclerView.setAdapter(new ImageAdapter(plateInfo));
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
//        recyclerView.post(() -> {
//            ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams();
//            ViewGroup.LayoutParams ivLayoutParams = imageView14.getLayoutParams();
//            ivLayoutParams.height = layoutParams.height + 20;
//        });
    }

    @Override
    public void initData() {
        if (UserInstance.isLogin()) {
            String gender = UserInstance.getLoginData().getGender();
            mPresenter.loadData(gender);
        } else {
            mPresenter.loadData("2");
        }
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {

    }

    @Override
    public void showEmpty() {

    }

    /**
     * 当用户登录后，更新用户信息
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        Loading.getInstance().dismiss();
        if (event.isLogin) {
            //初始化登录信息
            Glide.with(this).load(UserInstance.getLoginData().getHead_pic()).into(profileImage);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.d(TAG, "onResume: ");
//        if (alreadyShare) {
//            FriendBoostActivity.start(FreeBookActivity.this);
//            finish();
//            alreadyShare = false;
//        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        UMShareAPI.get(this).release();
    }

    @OnClick({R.id.tv_activity_rule, R.id.tv_join_in})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_activity_rule:
                WebViewActivity.start(this, "https://m.resouxs.com/activity/fifthrule", "活动规则");
                break;
            case R.id.tv_join_in:

                if (UserInstance.isLogin()) {
                    //分享
                    UMWeb web = new UMWeb("https://m.resouxs.com/activity/fifth?token=" + UserInstance.getToken());
//                    web.setTitle("全场免费看小说");
//                    web.setThumb(new UMImage(this, R.mipmap.logo));  //缩略图
//                    web.setDescription("限时免费一时爽，邀请好友一直爽！我刚刚在热搜小说APP分享了链接，又获得了一天免费时长~你也快来参加吧！");

                    new ShareAction(this)
                            .withMedia(web)
                            .setDisplayList(SHARE_MEDIA.QQ, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN_CIRCLE)
                            .setCallback(umShareListener).open();

                } else {
                    DialogManager.showLoginDialog(getSupportFragmentManager());
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private class ImageAdapter extends RecyclerView.Adapter<ImageHolder> {

        private List<MorePlateInfo> mInfoList;

        public ImageAdapter(List<MorePlateInfo> plateInfoList) {
            mInfoList = plateInfoList;
        }

        @NonNull
        @Override
        public ImageHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            ImageView imageView = new ImageView(viewGroup.getContext());
            imageView.post(() -> {
                ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                layoutParams.width = (int) mItemWidth;
                layoutParams.height = (int) mItemHeight;
            });
            return new ImageHolder(imageView);
        }

        @Override
        public void onBindViewHolder(@NonNull ImageHolder imageHolder, int i) {
            Glide.with(ReSouApplication.getRSApplication()).load(mInfoList.get(i).getNovelCover()).into((ImageView) imageHolder.itemView);
        }

        @Override
        public int getItemCount() {
            return mInfoList == null ? 0 : mInfoList.size();
        }
    }

    private class ImageHolder extends RecyclerView.ViewHolder {

        public ImageHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    boolean alreadyShare;

    private static final String TAG = "FreeBookActivity-App";

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            Log.d(TAG, "umeng onStart: ");
            switch (platform) {
                case WEIXIN:
                case WEIXIN_CIRCLE:
                    if (!WXUtils.isWeixinAvilible(FreeBookActivity.this)) {
                        ToastUtil.makeShortToast("您未安装微信，请选择其他分享方式");
                        return;
                    }
                    break;
                case QZONE:
                case QQ:
                    if (!WXUtils.isQQClientAvailable(FreeBookActivity.this)) {
                        ToastUtil.makeShortToast("您未安装QQ，请选择其他分享方式");
                        return;
                    }
                    break;
            }
            alreadyShare = true;
            mPresenter.startFifteenFreeActivity();

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d(TAG, "umeng onResult: ");
//            MessageEvent messageEvent = new MessageEvent();
//            messageEvent.isLogin = true;
//            EventBus.getDefault().post(messageEvent);
            FriendBoostActivity.start(FreeBookActivity.this);
            setResult(2);
            finish();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.d(TAG, "umeng onError: ");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Log.d(TAG, "umeng onCancel: ");
//            MessageEvent messageEvent = new MessageEvent();
//            messageEvent.isLogin = true;
//            EventBus.getDefault().post(messageEvent);
            FriendBoostActivity.start(FreeBookActivity.this);
            setResult(2);
            finish();
        }
    };
}
